"""
this is utils class for TCM project.

"""
import codecs
# import chardet
import os
import json
import requests
from meilisearch import Client

MEILISEARCH_URI = "http://192.168.2.230:7700"
MEILISEARCH_MASTERKEY = "janl-key"

meili_client = Client(MEILISEARCH_URI, MEILISEARCH_MASTERKEY)

def input_path(prompt, default_path):
    ret = default_path
    # while True:
    #     r = input(f"{prompt}: {default_path} :")
    #     if (r.strip() == ""):
    #         break
    #     else:
    #         if os.path.exists(r) and os.path.isdir(r):
    #             source_dir = r
    #             break
    #         else:
    #             continue
    return ret

def input_yes_no(prompt, default="Y"):
    ret = default
    # while True:
    #     r = input(f"{prompt}: {default} :")
    #     if (r.upper().strip() == "Y"):
    #         return True
    #     else:
    #         return False
    return True

def convert_dir_utf8(sdir, ddir):
    if ddir is None:
        ddir = sdir
    for file in os.listdir(sdir):
        if os.path.isfile(full_name := os.path.join(sdir, file)):
            dfn = full_name.replace(sdir, ddir)
            if os.path.exists(dfn):
                print(f"source filename:{full_name}, dest filename:{dfn} exist.")
                continue
            try:
                convert_to_utf8(full_name, dfn)
            except Exception as e:
                print(f"convert file:{full_name}, encode error:{e}")
        else:
            tmp_sdir = os.path.join(sdir, file)
            tmp_ddir = os.path.join(ddir, file)
            if not os.path.exists(tmp_ddir):
                os.mkdir(tmp_ddir)
            convert_dir_utf8(tmp_sdir, tmp_ddir)

def detect_encoding(file_path):
    """
    检测文件的编码格式
    :param file_path: 文件路径
    :return: 文件的编码格式
    """
    with open(file_path, 'rb') as file:
        raw_data = file.read()
        result = chardet.detect(raw_data)
        return result['encoding']

def convert_to_utf8(input_file, output_file=None):
    """
    将文件编码转换为 UTF-8
    :param input_file: 输入文件路径
    :param output_file: 输出文件路径（如果不指定，则覆盖原文件）
    """
    if output_file is None:
        output_file = input_file

    # 检测文件编码
    input_encoding = detect_encoding(input_file)
    #print(f"file:{input_file} detect encoding:{input_encoding}")
    if input_encoding is None:
        input_encoding = "GB2312"
    print(f"file:{input_file}, Detected encoding: {input_encoding}")
    if input_encoding == "utf-8":
        with open(input_file, "r", encoding="utf-8") as src, open(output_file, "w", encoding="utf-8") as dest:
            dest.write(src.read())
        print(f"File is UTF-8 copy {output_file}")
        return
    # 读取文件内容并转换为 UTF-8
    with codecs.open(input_file, 'r', encoding=input_encoding, errors='ignore') as infile:
        content = infile.read()

    # 写入 UTF-8 编码的文件
    with codecs.open(output_file, 'w', encoding='utf-8') as outfile:
        outfile.write(content)

    print(f"File converted to UTF-8 and saved as {output_file}")


def convert_txt_2_json(bookid, txt_file, json_dir="json"):
    """
    convert txt file to json file
    json style:
    {
        "book_id":1,
        "book_name":"神农本草经",
        "book_img":"",
        "book_sheets":xx,
        "book_auth":"孙星衍",
        "book_dynasty":"清",
        "book_year":"公元1644-1911年"
        "id":1,
        "sheet_list":""
        "sheet_title":"神农本草经",
        "sheet_content":"xxx"
    }
    :param bookid:
    :param txt_file:
    :param json_file:
    :return:
    """
    save_path = json_dir
    if save_path == "json":
        save_path = os.path.join(os.path.dirname(txt_file), json_dir)
    books = {}
    book = {}
    pages = []
    documents = []
    page = {}
    book_name = ""
    book_img = ""
    book_sheets = 0
    book_auth = ""
    book_dynasty = ""
    book_year = ""
    sheet_list = ""
    sheet_title = ""
    sheet_content = ""

    json_file_name = ""
    sheet_count = 1

    with open(txt_file, 'r', encoding="utf-8") as file:
        lines = file.readlines()
        for line in lines:
            if line.startswith("<目录>"):
                json_file_name = "book_" + str(bookid) + "_" + book_name+ "_sheet_" + str(sheet_count) + ".json"
                data = {}
                data["book_id"] = bookid
                data["book_name"] = book_name
                data["book_img"] = book_img
                data["book_sheets"] = sheet_count
                data["book_auth"] = book_auth
                data["book_dynasty"] = book_dynasty
                data["book_year"] = book_year

                data["id"] = sheet_count
                data["sheet_title"] = sheet_title
                data["sheet_content"] = sheet_content
                # add data to book dict, when the end update book_sheets field.
                books[json_file_name] = data
                # save book sheet
                sheet_list = line.replace("<目录>", "")
                sheet_list = sheet_list.replace("\n", "")
                sheet_list = sheet_list.replace("\r", "")
                sheet_list = sheet_list.strip()
                sheet_title = ""
                sheet_content = ""
                sheet_count = sheet_count + 1

            elif line.startswith("<篇名>"):
                sheet_title = line.replace("<篇名>", "")
                sheet_title = sheet_title.replace("\n", "")
                sheet_title = sheet_title.replace("\r", "")
                sheet_title = sheet_title.strip()
            elif line.startswith("内容："):
                sheet_content = line.replace("内容：", "")
                sheet_content = sheet_content.strip()
            elif line.startswith("属性："):
                sheet_content = line.replace("属性：", "")
                sheet_content = sheet_content.strip()
            elif line.startswith("书名："):
                book_name = line.replace("书名：", "")
                book_name = book_name.replace("\n", "")
                book_name = book_name.replace("\r", "")
                book_name = book_name.strip()
            elif line.startswith("作者："):
                book_auth = line.replace("作者：", "")
                book_auth = book_auth.replace("\n", "")
                book_auth = book_auth.replace("\r", "")
                book_auth = book_auth.strip()
                sheet_content = sheet_content + line
            elif line.startswith("朝代："):
                book_dynasty = line.replace("朝代：", "")
                book_dynasty = book_dynasty.replace("\n", "")
                book_dynasty = book_dynasty.replace("\r", "")
                book_dynasty = book_dynasty.strip()
                sheet_content = sheet_content + line
            elif line.startswith("年份："):
                book_year = line.replace("年份：", "")
                book_year = book_year.replace("\n", "")
                book_year = book_year.replace("\r", "")
                book_year = book_year.strip()
                sheet_content = sheet_content + line
            else:
                #c = line.replace("\n", "")
                #c = c.replace("\r", "")
                #c = c.strip()
                sheet_content = sheet_content + line

    # process last sheet data.

    json_file_name = "book_" + str(bookid) + "_" + book_name + "_sheet_" + str(sheet_count) + ".json"
    data = {}
    data["book_id"] = bookid
    data["book_name"] = book_name
    data["book_img"] = book_img
    data["book_sheets"] = sheet_count
    data["book_auth"] = book_auth
    data["book_dynasty"] = book_dynasty
    data["book_year"] = book_year
    data["id"] = sheet_count
    data["sheet_title"] = sheet_title
    data["sheet_content"] = sheet_content
    books[json_file_name] = data

    book["id"] = 0
    book["name"] = book_name
    book["sheets"] = sheet_count
    book["papers"] = sheet_count
    book["auth"] = book_auth
    book["dynasty"] = book_dynasty
    book["year"] = book_year
    book["status"] = 1
    book["sort"] = bookid
    # book_id = post_book(book)
    #print("book_id:", book_id)
    sort = 1
    for k, v in books.items():
        # v["book_sheets"] = sheet_count
        # print("json file:", k)
        # json_data = json.dumps(v, ensure_ascii=False, indent=4)
        # # print("json data:", json_data)
        # save_full_name = os.path.join(save_path, k)
        # if os.path.exists(save_full_name):
        #     print(f"json file:{save_full_name} exist skip it.")
        # else:
        #     with open(save_full_name, 'w', encoding="utf-8") as jsonfile:
        #         jsonfile.write(json_data)
        #     print(f"save json file:{save_full_name}")
        # if v["book_name"] != "":
        #     print(v)
        page = {}
        page["id"] = 0
        page["book_id"] = 0
        page["book_name"] = v["book_name"]
        page["title"] = v["sheet_title"]
        page["content"] = v["sheet_content"]
        page["status"] = 1
        page["sort"] = sort
        pages.append(page)
        # pageid = post_page(page)
        # page["id"] = pageid
        # documents.append(page)
        # print("page_id:", pageid)
        sort = sort + 1

    book["pages"] = pages
    # print(documents)
    # update_meilisearch_index("books", documents, "id")
    # print(book)
    return book


def update_meilisearch_index(index_name, data, index_field):
    curr_index = meili_client.index(index_name)
    curr_index.add_documents(data, index_field)


def post_book(book_data):
    url = "http://127.0.0.1:5000/zbook/book/save"
    response = requests.post(url, json=book_data)
    bookid = "0"
    if response.status_code == 200:
        # print("Post request successful with JSON data.")
        # print("Response:", response.json())
        result = response.json()
        bookid = result["msg"]
        # print(bookid)
    else:
        print(f"Request failed with status code {response.status_code}")

    return bookid

def post_page(page_data):
    url = "http://127.0.0.1:5000/zbook/page/save"
    response = requests.post(url, json=page_data)
    pageid = "0"
    if response.status_code == 200:
        # print("Post request successful with JSON data.")
        # print("Response:", response.json())
        result = response.json()
        pageid = result["msg"]
        # print(bookid)
    else:
        print(f"Request failed with status code {response.status_code}")

    return pageid